var request = require('request');
var rp = require('request-promise');

function getStatistical(callback) {

    var nowTime = new Date()
    var option = {
        url: "http://www.unicom-cloud.com:8082/web/api/report/AutoUniteAnalyse",
        method: "POST",
        headers: {
            "content-type": "application/x-www-form-urlencoded;",
        },
        form: {
            apiKey: 'admin',
            timestamp: global.timestamp,
            sign: global.sign,
            accessType: 'MGR',
            deployId: 'smsi_2',
            polymerization: 1,
            startDate: nowTime.Format('yyyy-MM-dd'),
            endDate: nowTime.Format('yyyy-MM-dd'),

        }
    }
    rp(option).then((body) => {
        var json = JSON.parse(body)
        if (json.data.length > 0) {
            var item = json.data[0]
            var str = '截至今日' + nowTime.Format('hh:mm:ss') +
                " \n提交数：" + item.submits +
                " \n成功数：" + item.succs +
                " \n失败数：" + item.fails +
                " \n未知数：" + item.unknowns +
                " \n成功率：" + ((item.succs / item.submits) * 100).toFixed(2) + "%" +
                " \n失败率：" + ((item.fails / item.submits) * 100).toFixed(2) + "%" +
                " \n未知率：" + ((item.unknowns / item.submits) * 100).toFixed(2) + "%"
            // console.log(str)
            // sendText(str)
            var failes = ((item.unknowns / item.submits) * 100).toFixed(2)
            // console.log(failes)
            global.sendText = str
            if( failes > 5){
                callback(true,str)
            }else{
                callback(false,str)
            }

        }
    })

    callback(true)
}

function sendText(str) {
    var serve = 'https://oapi.dingtalk.com/robot/send?access_token=44878f377c1d1e0e2c9b7886267387c9b77a0f2854c93d075d9aa9c1a464ab7d'
    var datas = {
        "msgtype": "text",
        "text": {
            "content":global.sendText
        }
    }
    request({
        url: serve,
        method: "POST",
        json: true,
        headers: {
            "content-type": "application/json",
        },
        body: datas
    }, function (error, response, body) {
        console.log(response)
        console.log(body)
    })
}

module.exports = {
    getStatistical,
    sendText
}